import { mapGetters } from "vuex";
export default {
  data() {
    return {
      myId: 1
    }
  },
  computed: {
    ...mapGetters(["viewType"]),
  },
  methods: {
    getID(list, index) {
      let i = index;
      list.map((item) => {
        i++;
        if (item.__config__.children && item.__config__.children.length > 0) {
          this.getID(item.__config__.children, i);
        }
      });
      return i;
    },
    // 复制组件
    copy(params) {
      let newId = ''
      if (this.viewType === 'drag') {
        newId = this.getID(this.componentsList, 0);
      } else {
        newId = new Date().getTime()
      }
      let a = JSON.parse(JSON.stringify({ ...params }));
      a.id = newId
      a["__field__"] = "field" + newId;
      a["__options__"].className = a["__componentName__"] + newId;
      if (a.echarts || a.html) {
        a["__options__"].id = "id" + newId;
      }
      if (this.viewType === 'drag' && ["rowComponent", "cardComponent"].includes(a["__componentName__"])) {
        a = this.createID(a);
      }
      this.setComponentsList(a);
      this.changeComponent(a);
    },
    // 保存当前配置到本地
    save(params) {
      this.$prompt("请输入组件名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValidator: (value) => {
          const a = this.componentsList.find((item) => item.label === value);
          if (!value) {
            return "输入不能为空";
          } else if (a) {
            return "组件名称重复";
          }
        },
      })
        .then(({ value }) => {
          params.label = value;
          this.saveHtmlComponent(params);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消保存",
          });
        });
    },
    // 递归复制组件时，创建新增id
    createID(params) {
      const dateTime = new Date().getTime();
      this.myId++;
      params.id = dateTime + this.myId;
      params["__field__"] = "field" + params.id;
      params["__options__"].className = params["__componentName__"] + params.id;
      if (params.echarts) {
        params["__options__"].id = "id" + params.id;
      }
      if (
        params["__config__"].children &&
        params["__config__"].children.length
      ) {
        params["__config__"].children.map((item) => {
          this.createID(item);
        });
      }
      return params;
    },
    remove(params) {
      this.$confirm("确认删除该组件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.removeComponentsList(params);
          const { length } = this.componentsList;
          if (length >= 1) {
            this.changeComponent(this.componentsList[length - 1]);
          } else {
            this.changeComponent("");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
